<?php

namespace App\Front;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreAppealRequest;
use App\Models\Appeal;
use App\Models\Village;
use App\Models\Wxuser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use MessageService;
class AppealController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = $request->title;
        $detail = $request->detail;
        $state = $request->state;
        if ($state == 'true') {
            $state = 1;
        }
        if ($state == 'false') {
            $state = 0;
        }

        $appeals = Appeal::when($title, function ($query) use ($title, $detail) {
            $query->where('title', 'like', '%'.$title."%");
        })
            ->when($detail, function ($query) use ($detail) {
                $query->where('detail', 'like', '%'.$detail."%");
            })
            ->where('state', $state)->orderByDesc('id')->paginate(10);
        return $appeals;
    }

    public function currUserAppeal(Request $request)
    {
        $wxuser = Auth::user();
        $title = $request->title;
        $detail = $request->detail;


        $appeals = Appeal::when($title, function ($query) use ($title, $detail) {
            $query->where('title', 'like', '%'.$title."%");
        })
            ->when($detail, function ($query) use ($detail) {
                $query->where('detail', 'like', '%'.$detail."%");
            })
            ->where('wxuser_id', $wxuser->id)->orderByDesc('id')->get();
        return $appeals;
    }

    public function store(StoreAppealRequest $request)
    {
        $request->validate([
            'category' => ['required'],
            'detail' => ['required'],
        ]);


        DB::beginTransaction();
        $appeal = Auth::user()->appeals()->create($request->input());

        //截取0，5，并用连接上...
        $shortTitle = Str::length($appeal->category) > 10 ?
            (Str::substr($appeal->category, 0, 10)."...") : $appeal->category;
        /**
         * 使用TEMPLATE_NOTICE_ID
         * 业务类型
         *
         * {{thing1.DATA}}
         * 申请时间
         *
         * {{date4.DATA}}
         * 提示说明
         *
         * {{thing5.DATA}}
         * 当前进度
         *
         * {{thing2.DATA}}
         */

        //获取当前时间
        $time = \Illuminate\Support\Carbon::now();

        $data =
            [
                "thing1" => ["value" => "政策咨询"],
                "date4" => ["value" => "{$time}"],
                "thing5" => ["value" => $shortTitle],
                "thing2" => ["value" => "系统已接收"]
            ];

        $village = Village::find($request->village_id)->first();

        $admins = $village->wxusers()->get();

        collect($admins)->map(function ($admin) use ($data) {
            MessageService::send(Wxuser::find($admin->id), "notice", $data);
        });
        //再通知管理员（微信用户）
        DB::commit();
        return $this->message('添加成功');
    }

    /**
     * Display the specified resource.
     *
     * @param \App\Models\Appeal $appeal
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, Appeal $appeal)
    {
        $wechatUser = Auth::guard('sanctum')->user();
        if($wechatUser){
            if ($appeal->wxuser_id==$wechatUser->id){
                if ($request->state == 'todo') {
                    return $appeal;
                }
                if ($request->state == 'done') {
                    $reply = $appeal->relies()->first();
                    return $appeal->toArray() +
                        [
                            'reply' => $reply,
                            "replyUser" => $appeal->appealable()->first()
                        ];
                }
            }
            return $this->error("无权访问");
        }else{
            return $this->error("无权访问");
        }
    }


    //添加回复
    public function reply(Request $request, Appeal $appeal)
    {


        //接收到发起人wxuser_id
        $wxuser_id = $request->wxuser_id;

        DB::beginTransaction();
        //更新事务状态   该事务已处理
        $appeal->state = true;
        $appeal->save();
        //1、添加回复内容（额外添加发起人的wxuser_id）
        $reply = $appeal->relies()->create($request->input());
        $appeal->refresh();
        //2、更新appeal表，添加回复人（user或者wxuser）
        $replyUser = Auth::user();
        $replyUser->replyAppeals()->save($appeal);
        //3、发送通知到发起人（通知该事务已经处理）
        /**
         * 使用TEMPLATE_REMIND_ID
         *    业务内容
         *
         * {{thing1.DATA}}
         * 受理单位
         *
         * {{thing4.DATA}}
         * 时间
         *
         * {{time5.DATA}}
         * 备注
         *
         * {{thing6.DATA}}
         * 业务进度
         *
         * {{thing3.DATA}}
         */
        $wxuser = Wxuser::where("id", $wxuser_id)->first();
        $notifyType = "remind";
        $shortTitle = Str::length($appeal->category) > 10 ?
            (Str::substr($appeal->category, 0, 10)."...") : $appeal->category;

        $shortRemark = Str::length($reply->remark) > 10 ?
            (Str::substr($reply->remark, 0, 10)."...") : $reply->remark;
        //class_basename如果是后台管理员，则Auth::user()为user模型，如果是手机端则为wxuser模型
        $modelType = class_basename(get_class(Auth::user()));
        $replyer = $modelType == 'Wxuser' ? "村干部：".Auth::user()->nickName : "后台管理员";
        $time = \Illuminate\Support\Carbon::now();
        $data =
            [
                "thing1" => ["value" => "{$shortTitle}"],
                "thing4" => ['value' => "{$replyer}"],
                "time5" => ["value" => "{$time}"],
                "thing6" => ["value" => "{$shortRemark}"],
                "thing3" => ["value" => "已完成"]
            ];


        MessageService::send($wxuser, $notifyType, $data);
        DB::commit();
        return $this->message('回复成功');
    }

}
